Tengo la siguiente interfaz:
export interface WithQueryBuilder { queryBuilderProps: { columns: { [key: string]: { enabled: boolean; label: string; key: string } }; meta: Record<string, unknown>; filters: Record<string, unknown>; search: { [key: string]: { enabled?: boolean; key: string; label: string; value: null | string }; }; page: number; sort: null; }; } Ahora quiero crear una nueva interfaz que consista en las propiedades de queryBuilderProps y algunas adicionales. Intenté lo siguiente:
interface TableProps extends Pick<WithQueryBuilder, 'queryBuilderProps'> { onUpdate?: () => void; }Lo que esperaba es un tipo como ese:
{ onUpdate: ..., columns: ..., filters: ..., search: ..., [...] }En cambio, el tipo se ve así:
{ onUpdate: ..., withQueryBuilder: { columns, meta, filters, ...), } Entiendo por qué sucede esto, pero me pregunto si hay una manera de "seleccionar" todas las definiciones secundarias en lugar de queryBuilderProps en su conjunto. Algo así como un operador de propagación para TypeScript.
¿Existe algo así?
Podemos usar un indexed access type para buscar una propiedad específica en otro tipo:
tipo Persona = { edad: número; nombre: cadena; vivo: booleano }; type Edad = Persona["edad"]; tipo Edad = número
Todavía puede usar la interface para sus TableProps de la siguiente manera:
export interface WithQueryBuilder { queryBuilderProps: { columns: { [key: string]: { enabled: boolean; label: string; key: string } }; meta: Record<string, unknown>; filters: Record<string, unknown>; search: { [key: string]: { enabled?: boolean; key: string; label: string; value: null | string }; }; page: number; sort: null; }; } // Here is the important part, this is the correct way to get the sub-type type QueryBuilderProps = WithQueryBuilder['queryBuilderProps'] // You can still use interface here interface TableProps extends QueryBuilderProps { onUpdate?: () => void; } const obj: TableProps = { onUpdate() {}, columns: { "key": { enabled: true, label: `label`, key: `key` }, }, meta: {}, filters: {}, search: {}, page: 1, sort: null, } // The following will throw error: // An interface can only extend an identifier/qualified-name with optional type arguments.(2499) interface TableProps2 extends WithQueryBuilder['queryBuilderProps'] { onUpdate?: () => void; }